#!/usr/bin/env python3
# rename_chapters.py

import re
import shutil
from pathlib import Path

def reformat_chapters(txt_path: Path, backup=True):
    """把 01、穿越 → 第01章 穿越"""
    if backup:
        shutil.copy2(txt_path, txt_path.with_suffix('.txt.bak'))

    # 自动识别编码
    try:
        text = txt_path.read_text(encoding='utf-8')
    except UnicodeDecodeError:
        text = txt_path.read_text(encoding='gbk')

    # 正则：匹配 数字+顿号+标题，直到行尾
    pattern = re.compile(r'^(\d+)、(.+)$', re.MULTILINE)

    new_text = pattern.sub(lambda m: f"第{m.group(1).zfill(2)}章 {m.group(2)}", text)

    txt_path.write_text(new_text, encoding='utf-8')
    print(f"✅ 已改写 {txt_path}")

# ----------- 使用示例 -----------
if __name__ == '__main__':
    file = Path('ysmc.txt')          # 改成你的文件名
    reformat_chapters(file)